package xyz.eden.cloud.common.mybatis.support.fill.annotation.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.springframework.stereotype.Component;
import xyz.eden.cloud.common.core.bean.ReflectUtils;
import xyz.eden.cloud.common.mybatis.support.fill.annotation.annotation.DateFieldFill;
import xyz.eden.cloud.common.mybatis.support.fill.annotation.annotation.IdGen;
import xyz.eden.cloud.common.mybatis.support.fill.annotation.annotation.OperateFieldFill;
import xyz.eden.cloud.common.mybatis.support.fill.annotation.context.MetaDataContext;
import xyz.eden.cloud.common.mybatis.support.fill.annotation.enums.DateType;
import xyz.eden.cloud.common.mybatis.support.fill.annotation.enums.FieldFillSchema;
import xyz.eden.cloud.common.mybatis.support.fill.annotation.enums.IdGenType;
import xyz.eden.cloud.common.web.did.IdGenFunction;
import xyz.eden.cloud.common.web.spring.BeanFactory;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

/**
 * 字段自动填充拦截器
 */
@Slf4j
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
@Component
public class FillAutoSupplementInterceptor implements Interceptor {

    private static final String INTERCEPTOR_NAME = "FillAutoSupplementInterceptor";

    /**
     * insert 字段填充模式列表
     */
    private static final List<FieldFillSchema> INSERT_FILL_SCHEMA_LIST = Arrays.asList(FieldFillSchema.INSERT, FieldFillSchema.INSERT_UPDATE);
    /**
     * update 字段填充模式列表
     */
    private static final List<FieldFillSchema> UPDATE_FILL_SCHEMA_LIST = Arrays.asList(FieldFillSchema.UPDATE, FieldFillSchema.INSERT_UPDATE);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        // SQL 类型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];

        if (Objects.isNull(sqlCommandType)) {
            log.debug("mybatis interceptor [{}] - sqlCommandType is null.", INTERCEPTOR_NAME);
            return invocation.proceed();
        }

        if (Objects.isNull(parameter)) {
            log.debug("mybatis interceptor [{}] - parameter is null.", INTERCEPTOR_NAME);
            return invocation.proceed();
        }

        switch (sqlCommandType) {
            case INSERT: {
                this.handleInsertSqlCommandType(parameter);
                break;
            }
            case UPDATE: {
                this.handleUpdateSqlCommandType(parameter);
                break;
            }
            default: {
                log.debug("mybatis interceptor [{}] - nonsupport sqlCommandType.", INTERCEPTOR_NAME);
            }
        }
        return invocation.proceed();
    }

    private void handleInsertSqlCommandType(Object parameter) {

        try {
            long currentTimeMillis = System.currentTimeMillis();
            MetaDataContext.OperateInfo operate = MetaDataContext.getOperate();

            // 获取字段列表
            Field[] fields = ReflectUtils.getAllFields(parameter);

            for (Field field : fields) {
                field.setAccessible(true);
                if (Objects.nonNull(field.get(parameter))) {
                    field.setAccessible(false);
                    continue;
                }

                // 填充日期
                DateFieldFill dateFieldFill;
                if (Objects.nonNull(dateFieldFill = field.getAnnotation(DateFieldFill.class))) {
                    DateType dateType = dateFieldFill.dateType();
                    if (INSERT_FILL_SCHEMA_LIST.contains(dateFieldFill.fillSchema())) {
                        Object dateVal = DateType.getDateVal(dateType, currentTimeMillis);
                        field.set(parameter, dateVal);
                    }
                }

                // 填充操作者
                OperateFieldFill operateFieldFill;
                if (Objects.nonNull(operateFieldFill = field.getAnnotation(OperateFieldFill.class))) {
                    if (INSERT_FILL_SCHEMA_LIST.contains(operateFieldFill.fillSchema())) {
                        if (operate != null) {
                            field.set(parameter, operate.getUsername());
                        }
                    }
                }

                // id 生成
                IdGen idGen;
                if (Objects.nonNull(idGen = field.getAnnotation(IdGen.class))) {
                    if (INSERT_FILL_SCHEMA_LIST.contains(idGen.fillSchema())) {
                        IdGenType type = idGen.type();
                        IdGenFunction idGenFunction = BeanFactory.getBean(IdGenFunction.class);
                        Long id = idGenFunction.getId(type.getCode());
                        field.set(parameter, id);
                    }
                }
                field.setAccessible(false);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            MetaDataContext.clearOperate();
        }

    }

    protected void handleUpdateSqlCommandType(Object parameter) {
        try {
            long currentTimeMillis = System.currentTimeMillis();
            MetaDataContext.OperateInfo operate = MetaDataContext.getOperate();

            Object newParameter = parameter;
            if (parameter instanceof MapperMethod.ParamMap p) {
                if (p.containsKey("et")) {
                    newParameter = p.get("et");
                } else {
                    newParameter = p.get("param1");
                }
            }
            Field[] fields = ReflectUtils.getAllFields(newParameter);

            for (Field field : fields) {
                field.setAccessible(true);
                if (Objects.nonNull(field.get(parameter))) {
                    field.setAccessible(false);
                    continue;
                }

                // 填充日期
                DateFieldFill dateFieldFill;
                if (Objects.nonNull(dateFieldFill = field.getAnnotation(DateFieldFill.class))) {
                    DateType dateType = dateFieldFill.dateType();
                    if (UPDATE_FILL_SCHEMA_LIST.contains(dateFieldFill.fillSchema())) {
                        Object dateVal = DateType.getDateVal(dateType, currentTimeMillis);
                        field.set(parameter, dateVal);
                    }
                }
                // 填充操作者
                OperateFieldFill operateFieldFill;
                if (Objects.nonNull(operateFieldFill = field.getAnnotation(OperateFieldFill.class))) {
                    if (UPDATE_FILL_SCHEMA_LIST.contains(operateFieldFill.fillSchema())) {
                        if (operate != null) {
                            field.set(parameter, operate.getUsername());
                        }
                    }
                }
                field.setAccessible(false);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            MetaDataContext.clearOperate();
        }
    }

    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }
}
